package com.grape.service.system.impl;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grape.dao.system.MenuRepository;
import com.grape.domain.system.Menu;
import com.grape.domain.system.Role;
import com.grape.domain.system.User;
import com.grape.service.system.MenuService;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuRepository mr;
	
	@Override
	public Page<Menu> findAll(Pageable pageable) {
		return mr.findAll(pageable);
	}

	@Override
	@CacheEvict(value="menu",allEntries=true)
	public void save(Menu model) {
		// 防止用户没有选择父级菜单导致无法保存
		if (model.getParentMenu()!=null && model.getParentMenu().getId() == null) {
			model.setParentMenu(null);
		}
		mr.save(model);
	}

	@Override
	public List<Menu> findByUser(User user) {
		// 后门
		if (user.getUsername().equals("admin")) {
			return mr.findAll(); 
		}
		
		List<Menu> list = new ArrayList<>();
		Set<Role> roles = user.getRoles();
		
		for (Role role : roles) {
			list.addAll(role.getMenus());
		}
		return list;
	}

	@Override
	@Cacheable("menu")
	public List<Menu> findAll() {
		System.out.println("配置了菜单缓存，应该只查一次");
		return mr.findAll();
	}



}
